import { useEffect, useState } from "react";
import { useInterval } from "ahooks";

/**
 * 当前时间是否在交易时间内
 * @returns {boolean}
 */
const isMarketOpen = (): boolean => {
  const now = new Date();
  const day = now.getDay();

  // 节假日或周末
  if (day === 0 || day === 6) return false;

  const marketActingTime = [
    {
      open: "09:30",
      close: "11:30",
    },
    {
      open: "13:00",
      close: "15:00",
    },
  ];

  const currentMinutes = now.getHours() * 60 + now.getMinutes();

  return marketActingTime.some(({ open, close }) => {
    const [openHour, openMinute] = open.split(":").map(Number);
    const [closeHour, closeMinute] = close.split(":").map(Number);

    const openMinutes = openHour * 60 + openMinute; // 开盘时间转为分钟数
    const closeMinutes = closeHour * 60 + closeMinute; // 收盘时间转为分钟数

    // 判断当前时间是否在开盘和收盘时间之间
    return currentMinutes >= openMinutes && currentMinutes <= closeMinutes;
  });
};

/**
 * 时钟组件
 */
export default function Clock({
  /**
   * 是否显示时钟
   * @default true
   */
  showClock = true,
  /**
   * 多次秒请求一次
   * @default 60
   */
  interval = 60,
  /**
   * 分钟变化时触发的回调，按照 interval 触发
   */
  onMinuteChange,
}: {
  showClock?: boolean;
  interval?: number;
  onMinuteChange?: () => void;
}) {
  const [currentTime, setCurrentTime] = useState(() => {
    const now = new Date();

    return now.toLocaleTimeString("zh-CN", { hour12: false });
  });

  const [isPageVisibleState, setIsPageVisibleState] = useState(() => {
    return document.visibilityState === "visible";
  });
  const [activeMarket, setActiveMarket] = useState<boolean>();

  useInterval(async () => {
    setIsPageVisibleState(document.visibilityState === "visible");
    const now = new Date();
    const seconds = now.getSeconds();

    setActiveMarket(isMarketOpen());

    if (
      seconds % interval === 0 &&
      isPageVisibleState &&
      onMinuteChange &&
      activeMarket
    ) {
      onMinuteChange();
    }

    setCurrentTime(now.toLocaleTimeString("zh-CN", { hour12: false }));
  }, 1000);

  // 当页面可见时，立即请求一次
  useEffect(() => {
    if (
      isPageVisibleState &&
      typeof onMinuteChange === "function" &&
      activeMarket
    ) {
      onMinuteChange();
    }
  }, [isPageVisibleState]);

  return (
    <>
      {showClock && (
        <div className="flex items-center gap-2">
          {activeMarket !== null && (
            <div
              className={`h-2 w-2 box-content rounded-full border-4 border-solid ${
                activeMarket
                  ? "bg-[#22ab94] border-green-100 "
                  : "bg-yellow-500 border-none"
              }`}
            />
          )}
          <span className="min-w-[68px]">{currentTime}</span>
        </div>
      )}
    </>
  );
}
